/**
 * 自定义Hook
 * 需求：定义一个hook实现本地存储的操作
 */
 import React,{ useState } from 'react';

 export function useStorage(key) {
     let initValue = localStorage.getItem(key); // '{}','[{}]','hello'
 
     try {
         initValue = JSON.parse(initValue);
     } catch (err) {
 
     }
 
     const [value, setValue] = useState(initValue);
 
     const changeValue = function (newValue) {
         // 如果newValue为对象，需要转成json
         if (typeof newValue === 'object') {
             localStorage.setItem(key, JSON.stringify(newValue))
         } else {
             localStorage.setItem(key, newValue)
         }
 
         setValue(newValue)
     }
 
     return [
         value,
         changeValue
     ]
 }